import { getLogger } from '@gnlab/utils'

/**
 * 记录页面处于“前台”还是“后台”
 */
const logger = getLogger('ui/visible')

function record() {
  logger.info(`页面进入 ${document.hidden ? '后台' : '前台'} 状态`)
}

export function recordVisible() {
  setTimeout(() => {
    record()
    document.addEventListener('visibilitychange', record)
  }, 1000)
}

/**
 * 返回页面当前的“前后台”状态
 */
export function usePageVisible() {
  const [visible, setVisible] = useState(() => !document.hidden)
  document.addEventListener('visibilitychange', () => setVisible(!document.hidden))
  return visible
}
